<!DOCTYPE html>
<html lang="en">
  <head>
    <title>
        Java-EE-Servlet - rulerLwx Blog
      </title>
        <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
      content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
    <meta name="renderer" content="webkit">
    <meta http-equiv="Cache-Control" content="no-transform" />
    <meta http-equiv="Cache-Control" content="no-siteapp" />
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="format-detection" content="telephone=no,email=no,adress=no">
    
    <meta name="theme-color" content="#000000" />
    
    <meta http-equiv="window-target" content="_top" />
    
    
    <meta name="description" content="JSP JSP的本质是Servlet，JSP页面由系统编译成Servlet，Servlet再负责响应用户请求。 语法 1、注释 &amp;lt;%&amp;ndash;" />
    <meta name="generator" content="Hugo 0.73.0 with theme pure" />
    <title>Java-EE-Servlet - rulerLwx Blog</title>
    
    
    <link rel="stylesheet" href="https://rulerLwx.gitee.io/css/style.min.c4bc7071f132c964c2116bca53b392933f377e5ca7b7051ed245187c621a2d3e.css">
    
    <link rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/9.15.10/styles/github.min.css" async>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.4.2/tocbot.css" async>
    <meta property="og:title" content="Java-EE-Servlet" />
<meta property="og:description" content="JSP JSP的本质是Servlet，JSP页面由系统编译成Servlet，Servlet再负责响应用户请求。 语法 1、注释 &lt;%&ndash;" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://rulerLwx.gitee.io/2020/07/java-ee-servlet/" />
<meta property="article:published_time" content="2020-07-01T18:58:47+08:00" />
<meta property="article:modified_time" content="2020-07-01T18:58:47+08:00" />
<meta itemprop="name" content="Java-EE-Servlet">
<meta itemprop="description" content="JSP JSP的本质是Servlet，JSP页面由系统编译成Servlet，Servlet再负责响应用户请求。 语法 1、注释 &lt;%&ndash;">
<meta itemprop="datePublished" content="2020-07-01T18:58:47&#43;08:00" />
<meta itemprop="dateModified" content="2020-07-01T18:58:47&#43;08:00" />
<meta itemprop="wordCount" content="4505">



<meta itemprop="keywords" content="" /><meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="Java-EE-Servlet"/>
<meta name="twitter:description" content="JSP JSP的本质是Servlet，JSP页面由系统编译成Servlet，Servlet再负责响应用户请求。 语法 1、注释 &lt;%&ndash;"/>

    <!--[if lte IE 9]>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/classlist/1.1.20170427/classList.min.js"></script>
      <![endif]-->

    <!--[if lt IE 9]>
        <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
      <![endif]-->
  </head>

  
  

  <body class="main-center theme-black" itemscope itemtype="http://schema.org/WebPage"><header class="header" itemscope itemtype="http://schema.org/WPHeader">
    <div class="slimContent">
      <div class="navbar-header">
        <div class="profile-block text-center">
          <a id="avatar" href="https://gitee.com/rulerLwx" target="_blank">
            <img class="img-circle img-rotate" src="https://rulerLwx.gitee.io/avatar.png" width="200" height="200">
          </a>
          <h2 id="name" class="hidden-xs hidden-sm">rulerLwx</h2>
          <h3 id="title" class="hidden-xs hidden-sm hidden-md">thinking...</h3>
          <small id="location" class="text-muted hidden-xs hidden-sm"><i class="icon icon-map-marker"></i>Guangzhou, China</small>
        </div><div class="search" id="search-form-wrap">
    <form class="search-form sidebar-form">
        <div class="input-group">
            <input type="text" class="search-form-input form-control" placeholder="Search" />
            <span class="input-group-btn">
                <button type="submit" class="search-form-submit btn btn-flat" onclick="return false;"><i
                        class="icon icon-search"></i></button>
            </span>
        </div>
        <div class="ins-search">
            <div class="ins-search-mask"></div>
            <div class="ins-search-container">
                <div class="ins-input-wrapper">
                    <input type="text" class="ins-search-input" placeholder="Type something..."
                        x-webkit-speech />
                    <button type="button" class="close ins-close ins-selectable" data-dismiss="modal"
                        aria-label="Close"><span aria-hidden="true">×</span></button>
                </div>
                <div class="ins-section-wrapper">
                    <div class="ins-section-container"></div>
                </div>
            </div>
        </div>
    </form>
</div>
        <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
      </div>
      <nav id="main-navbar" class="collapse navbar-collapse" itemscope itemtype="http://schema.org/SiteNavigationElement" role="navigation">
        <ul class="nav navbar-nav main-nav">
            <li class="menu-item menu-item-home">
                <a href="/">
                    <i class="icon icon-home-fill"></i>
                  <span class="menu-title">Home</span>
                </a>
            </li>
            <li class="menu-item menu-item-archives">
                <a href="/posts/">
                    <i class="icon icon-archives-fill"></i>
                  <span class="menu-title">Archives</span>
                </a>
            </li>
            <li class="menu-item menu-item-categories">
                <a href="/categories/">
                    <i class="icon icon-folder"></i>
                  <span class="menu-title">Categories</span>
                </a>
            </li>
            <li class="menu-item menu-item-tags">
                <a href="/tags/">
                    <i class="icon icon-tags"></i>
                  <span class="menu-title">Tags</span>
                </a>
            </li>
            <li class="menu-item menu-item-about">
                <a href="/about/">
                    <i class="icon icon-cup-fill"></i>
                  <span class="menu-title">About</span>
                </a>
            </li>
        </ul>
      </nav>
    </div>
  </header>

<aside class="sidebar" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    
      <div class="widget">
    <h3 class="widget-title">Board</h3>
    <div class="widget-body">
        <div id="board">
            <div class="content">enjoy~
            </div>
        </div>
    </div>
</div>

      <div class="widget">
    <h3 class="widget-title"> Categories</h3>
    <div class="widget-body">
        <ul class="category-list">
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-framework/" class="category-list-link">java-framework</a><span class="category-list-count">38</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-front-end/" class="category-list-link">java-front-end</a><span class="category-list-count">11</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-se/" class="category-list-link">java-se</a><span class="category-list-count">21</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-senior/" class="category-list-link">java-senior</a><span class="category-list-count">4</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/linux/" class="category-list-link">linux</a><span class="category-list-count">13</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/tools/" class="category-list-link">tools</a><span class="category-list-count">1</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/%E6%8A%80%E6%9C%AF%E6%9D%82%E7%83%A9/" class="category-list-link">技术杂烩</a><span class="category-list-count">4</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/%E6%95%B0%E6%8D%AE%E5%BA%93/" class="category-list-link">数据库</a><span class="category-list-count">15</span></li>
        </ul>
    </div>
</div>
      <div class="widget">
    <h3 class="widget-title"> Tags</h3>
    <div class="widget-body">
        <ul class="tag-list">
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/jvm/" class="tag-list-link">jvm</a><span
                    class="tag-list-count">1</span></li>
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/%E5%A4%9A%E7%BA%BF%E7%A8%8B/" class="tag-list-link">多线程</a><span
                    class="tag-list-count">2</span></li>
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B/" class="tag-list-link">网络编程</a><span
                    class="tag-list-count">3</span></li>
            
        </ul>

    </div>
</div>
      
<div class="widget">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget-body">
        <ul class="recent-post-list list-unstyled no-thumbnail">
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E8%87%AA%E5%B7%B1%E5%8A%A8%E6%89%8B%E4%B8%80%E6%89%B9%E9%87%8F%E7%A7%BB%E5%8A%A8%E9%87%8D%E5%91%BD%E5%90%8D%E6%96%87%E4%BB%B6/" class="title">自己动手（一）——批量移动、重命名文件</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-27 17:50:02 &#43;0800 CST" itemprop="datePublished">2020-07-27</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E5%85%B3%E4%BA%8Einteger%E7%9A%84-128~127%E7%BC%93%E5%AD%98/" class="title">关于Integer的 -128~127缓存</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-11 16:56:21 &#43;0800 CST" itemprop="datePublished">2020-07-11</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E8%B7%A8%E5%9F%9F%E9%97%AE%E9%A2%98/" class="title">跨域问题</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-08 22:41:12 &#43;0800 CST" itemprop="datePublished">2020-07-08</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E4%B8%AA%E4%BA%BA%E5%8D%9A%E5%AE%A2%E6%90%AD%E5%BB%BA/" class="title">个人博客搭建</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-05 18:58:47 &#43;0800 CST" itemprop="datePublished">2020-07-05</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/centos/" class="title">CentOS-</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-01 18:58:47 &#43;0800 CST" itemprop="datePublished">2020-07-01</time>
                    </p>
                </div>
            </li>
        </ul>
    </div>
</div>
  </div>
</aside>

    
    
<aside class="sidebar sidebar-toc collapse" id="collapseToc" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    <h4 class="toc-title">Catalogue</h4>
    <nav id="toc" class="js-toc toc">

    </nav>
  </div>
</aside>
<main class="main" role="main"><div class="content">
  <article id="-" class="article article-type-" itemscope
    itemtype="http://schema.org/BlogPosting">
    
    <div class="article-header">
      <h1 itemprop="name">
  <a
    class="article-title"
    href="/2020/07/java-ee-servlet/"
    >Java-EE-Servlet</a
  >
</h1>

      <div class="article-meta">
        
<span class="article-date">
  <i class="icon icon-calendar-check"></i>&nbsp;
<a href="https://rulerLwx.gitee.io/2020/07/java-ee-servlet/" class="article-date">
  <time datetime="2020-07-01 18:58:47 &#43;0800 CST" itemprop="datePublished">2020-07-01</time>
</a>
</span>
<span class="article-category">
  <i class="icon icon-folder"></i>&nbsp;
  <a class="article-category-link" href="/categories/java-se/"> Java-Se </a>
</span>

        <span class="post-comment"><i class="icon icon-comment"></i>&nbsp;<a href="/2020/07/java-ee-servlet/#comments"
            class="article-comment-link">Comments</a></span>
		<span class="post-wordcount hidden-xs" itemprop="wordCount">Word Count: 4505words</span>
		<span class="post-readcount hidden-xs" itemprop="timeRequired">Read Count: 9minutes </span>
      </div>
    </div>
    <div class="article-entry marked-body js-toc-content" itemprop="articleBody">
      <h1 id="jsp">JSP</h1>
<p>JSP的本质是Servlet，JSP页面由系统编译成Servlet，Servlet再负责响应用户请求。</p>
<h2 id="语法">语法</h2>
<p>1、注释</p>
<p>&lt;%&ndash;注释内容 &ndash;%&gt;</p>
<p>2、声明</p>
<p>&lt;%! 声明部分 %&gt;</p>
<pre><code class="language-jsp">&lt;/head&gt;
&lt;!-- 下面是JSP声明部分 --&gt;
&lt;%!
    //声明一个整形变量
    public int count;

    //声明一个方法
    public String info() {
        return &quot;hello&quot;;
    }
%&gt;
&lt;body&gt;
&lt;%
    //将count的值输出后再加1
    out.println(count++);
%&gt;
&lt;br/&gt;
&lt;%
    //输出info()方法的返回值
    out.println(info());
%&gt;
&lt;/body&gt;
</code></pre>
<p>3、输出</p>
<p>&lt;%=表达式 %&gt;</p>
<p>4、脚本</p>
<p>&lt;%  脚本 %&gt;</p>
<pre><code>&lt;table bgcolor=&quot;#9999dd&quot; border=&quot;1&quot; width=&quot;300px&quot;&gt;
    &lt;!-- Java脚本，这些脚本会对HTML的标签产生作用 --&gt;
    &lt;%
        for (int i = 0; i &lt; 10; i++) {
    %&gt;
    &lt;!-- 上面的循环将控制&lt;tr&gt;标签循环 --&gt;
    &lt;tr&gt;
        &lt;td&gt;循环值:&lt;/td&gt;
        &lt;td&gt;&lt;%=i%&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;%
        }
    %&gt;
&lt;/table&gt;
</code></pre>
<p>以上四点都是在jsp页面中写，会将五jsp中的java代码和html标签编译成一个servlet。</p>
<h2 id="编译指令">编译指令</h2>
<ul>
<li>page：针对当前页面的指令。</li>
<li>include：包含另一个页面。</li>
<li>taglib：定义和访问自定义标签。</li>
</ul>
<p>语法：&lt;%@编译指令 属性名=”属性值” &hellip;.%&gt;</p>
<p>page指令的属性：</p>
<p><img src="https://gitee.com/rulerLwx/PicGo/raw/master/img/20200707160349.png" alt="image"></p>
<p>taglib指令：<code>&lt;%@ taglib prefix=&quot;c&quot; uri=&quot;http://java.sun.com/jsp/jstl/core&quot; %&gt; </code></p>
<p>include指令：<code>&lt;%@ include file=”relativeURLSpec”%&gt;</code></p>
<p>这个是静态include，<strong>它会把目标页面的其它编译指令也包含进来，但动态include则不会</strong>。</p>
<p>特点：包含页面在编译时将完全包含了被包含的页面的代码，如果两个页面的编译指令冲突，则页面报错。</p>
<p>注：动态include，使用<a href="jsp:include">jsp:include</a></p>
<h2 id="7个动作指令">7个动作指令</h2>
<ul>
<li>jsp:forward  执行页面转向，将请求的处理转发到下一个页面。</li>
<li>jsp:param  用于传递参数，必须与其他支持参数的标签一起使用</li>
</ul>
<pre><code>&lt;%@ page contentType=&quot;text/html; charset=GBK&quot; language=&quot;java&quot; errorPage=&quot;&quot; %&gt;
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot;
	&quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;
&lt;head&gt;
	&lt;title&gt; forward的原始页 &lt;/title&gt;
	&lt;meta name=&quot;website&quot; content=&quot;http://www.crazyit.org&quot; /&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h3&gt;forward的原始页&lt;/h3&gt;
&lt;jsp:forward page=&quot;forward-result.jsp&quot;&gt;
	&lt;jsp:param name=&quot;age&quot; value=&quot;29&quot;/&gt;
&lt;/jsp:forward&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<ul>
<li>
<p>jsp:include  用于动态引入一个JSP页面</p>
<p>它不会导入被include页面的编译指令，仅仅将<strong>被导入页面的body内容</strong>插入本页面。</p>
</li>
</ul>
<pre><code>&lt;body&gt;
&lt;jsp:include page=&quot;forward-result.jsp&quot; &gt;
	&lt;jsp:param name=&quot;age&quot; value=&quot;32&quot;/&gt;
&lt;/jsp:include&gt;
&lt;/body&gt;
</code></pre>
<ul>
<li>jsp:plugin 用于下载JavaBean或者Applet到客户端执行</li>
<li>jsp:useBean 创建一个Javabean实例</li>
<li>jsp:setProperty  设置JavaBean实例的属性值</li>
<li>jsp:getProperty  获取JavaBean实例的属性值</li>
</ul>
<h2 id="9个内置对象">9个内置对象</h2>
<p>request、response、session、application、out、pagecontext、config、page、exception。</p>
<p><img src="https://gitee.com/rulerLwx/PicGo/raw/master/img/20200707160459.png" alt="image"></p>
<p>pageContext可以访问page、request、session、application范围的变量。</p>
<h2 id="el表达式">EL表达式</h2>
<p>语法：${expression}</p>
<p>JSP2才开始默认支持EL表达式。</p>
<p>（如果web.xml中使用2.3及以下dtd，则需在使用el表达式的页面中增加<code>&lt;%@page isELIgnored=&quot;false&quot; %&gt;</code>配置，el表达式才会生效。如果web.xml中使用2.4及以上dtd，则默认isELIgnored=&quot;false&rdquo;）</p>
<h3 id="11个内置对象">11个内置对象</h3>
<ul>
<li>pageContext，与JSP的pageContext内置对象相同；</li>
<li>pageScope，page范围内的属性值；</li>
<li>requestScope，request范围内的属性值；</li>
<li>sessionScope，session范围内的属性值；</li>
<li>applicationScope，application范围的属性值；</li>
<li>param，请求参数</li>
<li>paramValues，以数组形式表示的请求参数；</li>
<li>header，获取请求头；</li>
<li>headerValues，获取以数组形式表示的请求头；</li>
<li>initParam，获取Web应用初始化参数；</li>
<li>cookie，获取Cookie值。</li>
</ul>
<h3 id="使用示例">使用示例</h3>
<p>1、依赖的包</p>
<pre><code>&lt;dependency&gt;
	&lt;groupId&gt;jstl&lt;/groupId&gt;
	&lt;artifactId&gt;jstl&lt;/artifactId&gt;
	&lt;version&gt;1.2&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
	&lt;groupId&gt;taglibs&lt;/groupId&gt;
	&lt;artifactId&gt;standard&lt;/artifactId&gt;
	&lt;version&gt;1.1.2&lt;/version&gt;
&lt;/dependency&gt;
</code></pre>
<p>2、jsp页面引入 c标签</p>
<p><code>&lt;%@ taglib prefix=&quot;c&quot; uri=&quot;http://java.sun.com/jsp/jstl/core&quot; %&gt;</code></p>
<p>在jsp中拿到绝对路径：</p>
<pre><code>&lt;form action=&quot;${pageContext.request.contextPath }/emp&quot;&gt;

&lt;/form&gt;
</code></pre>
<p>在开发中推荐使用绝对路径</p>
<h1 id="servlet">Servlet</h1>
<p>Servlet是个特殊的Java类，必须继承HttpServlet。</p>
<pre><code>public class MyServlet extends HttpServlet{

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        
    }
    
}
</code></pre>
<p>Servlet中没有内置对象。</p>
<h2 id="入门demo">入门Demo</h2>
<p>servlet3.0开始，servlet的配置有两种方式：</p>
<ul>
<li>web.xml。</li>
<li>在servlet类中使用@WebServlet注解。</li>
</ul>
<h3 id="webxml方式">web.xml方式</h3>
<p>1）创建Maven工程，导入依赖；</p>
<p>2）创建的Servlet，继承HttpServlet，重写doGet/doPost方法；</p>
<p>3）在web.xml配置servlet和servlet-mapping，其中<code>&lt;url-pattern&gt;/servletTest&lt;/url-pattern&gt;</code>要有<code>/</code></p>
<p>4）将工程发布到Tomcat测试访问</p>
<h3 id="零配置方式">零配置方式</h3>
<p>1）创建Maven工程，导入依赖；</p>
<p>2）创建的Servlet，继承HttpServlet，重写doGet/doPost方法；</p>
<p>3）用@WebServlet注解此Servlet类，<code>@WebServlet(name = &quot;testServlet&quot;,urlPatterns = {&quot;/testServlet&quot;})</code>；</p>
<p>4）将工程发布到Tomcat测试访问</p>
<p>@WebServlet支持的常用属性：</p>
<p><img src="E:%5Cbackup%5Chogo_blog%5Ccontent%5Cposts%5CJava-Se%5C1CD4254B5F8048B0B830065C5C82E9AD" alt="image"></p>
<p>loadOnStartup属性只接收一个整型值，值越小，优先级越高。</p>
<p>注意：Tomcat容器自动加载有@WebServlet注解的类</p>
<p>容器是如何加载@WebServlet类的？如何发现servlet的？？TODO&hellip;.</p>
<h3 id="两种方式比较">两种方式比较</h3>
<p>使用的不同之处是第三步，其它的相同。</p>
<p>一个工程中两种方式同时使用时，Servlet的name属性不能相同；若相同，web.xml中的优先，零配置的访问不到。</p>
<h2 id="servlet生命周期">Servlet生命周期</h2>
<p>servelt的创建、销毁都不是由程序员来决定的，而是由Web容器进行控制。</p>
<p>创建servlet实例有两个时机：</p>
<ul>
<li>客户端第一次访问某个servlet时</li>
<li>web容器启动时，需要配置load-on-startup属性</li>
</ul>
<p>servlet生命周期：</p>
<p>1、创建servlet实例。</p>
<p>2、调用servlet的init方法。</p>
<p>3、servlet初始化后，将一直存在容器中，用于响应客户端请求。一般处理的是GET/POST请求，分别调用doGet/doPost方法响应请求。</p>
<p>4、容器决定销毁servlet时，先调用servlet的destroy方法。</p>
<p>注意：在整个Servlet的生命周期过程中，创建Servlet实例、调用实例的init()和destroy()方法都只进行一次，当初始化完成后，Servlet容器会将该实例保存在内存中，通过调用它的service()方法，为接收到的请求服务。换句话说，<strong>容器中的Servlet是单例的</strong>。</p>
<h2 id="访问servlet配置参数">访问servlet配置参数</h2>
<p>容器在初始化servlet时，将调用servlet的<code>init(ServletConfig config)</code>方法，config就封装好了servlet的初始化参数，通过它就可以访问配置参数了。</p>
<p><code>config.getInitParameter(&quot;&quot;)</code>;</p>
<h2 id="自定义标签">自定义标签</h2>
<p>TODO&hellip;.</p>
<h2 id="filter">Filter</h2>
<p>filter的流程：对用户请求进行预处理，然后将请求交给servlet进行处理并生成响应，最后再对服务响应进行后处理。</p>
<p>filter的使用：</p>
<p>1、创建filter实现类</p>
<p>必须实现javax.servlet.Filter接口，此接口有如下三个方法：</p>
<ul>
<li>void init(FilterConfig config)，config是Filter的配置参数。</li>
<li>void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)：在chain.doFilter(req,resp)之前的是预处理，之后的代码是后处理。如果不调用chain.doFilter(req,resp)方法，则此此用户请求不会交给servlet处理。</li>
<li>void destroy()</li>
</ul>
<p>2、配置filter</p>
<ul>
<li>web.xml配置方式</li>
<li>@WebFilter注解方式</li>
</ul>
<p>@WebFilter支持的常用属性</p>
<p><img src="E:%5Cbackup%5Chogo_blog%5Ccontent%5Cposts%5CJava-Se%5C194B76B103724412A5B854C74D43919E" alt="image"></p>
<p>filter跟servlet具有相同的生命周期行为。</p>
<h2 id="listener">Listener</h2>
<p>用于监听web应用的内部事件，如web应用的启动、停止，用户session的开始、结束，用户请求到过等。</p>
<p>不同的监听器接口具有不同的作用：</p>
<ul>
<li>ServletContextListener，监听Web应用的启动和关闭。</li>
<li>ServletContextAttributeListener，监听ServletContext范围（application）内属性的改变。</li>
<li>ServletRequestListener，监听用户请求。</li>
<li>ServletRequestAttributeListener，监听ServletRequest范围（request）内属性的改变。</li>
<li>HttpSessionListener，监听Session的开始、结束。</li>
<li>HttpSessionActivationListener，监听HttpSession范围（session）内属性的改变。</li>
</ul>
<p>listener的使用：</p>
<p>1、创建listener的实现类</p>
<p>2、@WebListener注解或web.xml方式配置listener。</p>
<h1 id="附件">附件</h1>
<h2 id="servlet依赖的jar包">Servlet依赖的jar包</h2>
<pre><code>3.1
&lt;dependency&gt;
	&lt;groupId&gt;javax.servlet&lt;/groupId&gt;
	&lt;artifactId&gt;javax.servlet-api&lt;/artifactId&gt;
	&lt;version&gt;3.1.0&lt;/version&gt;
&lt;/dependency&gt;

2.4
&lt;dependency&gt;
	&lt;groupId&gt;javax.servlet&lt;/groupId&gt;
	&lt;artifactId&gt;servlet-api&lt;/artifactId&gt;
	&lt;version&gt;2.4&lt;/version&gt;
	&lt;scope&gt;provided&lt;/scope&gt;
&lt;/dependency&gt;
</code></pre>
<h2 id="el表达式依赖的jar包">EL表达式依赖的jar包</h2>
<pre><code>&lt;dependency&gt;
	&lt;groupId&gt;jstl&lt;/groupId&gt;
	&lt;artifactId&gt;jstl&lt;/artifactId&gt;
	&lt;version&gt;1.2&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
	&lt;groupId&gt;taglibs&lt;/groupId&gt;
	&lt;artifactId&gt;standard&lt;/artifactId&gt;
	&lt;version&gt;1.1.2&lt;/version&gt;
&lt;/dependency&gt;
</code></pre>
<p>据说 jstl 1.2 不再需要 standard 这个包了：https://blog.csdn.net/z69183787/article/details/38066239</p>
<h2 id="webxml配置头">web.xml配置头</h2>
<pre><code>3.1
&lt;?xml version=&quot;1.0&quot; encoding=&quot;GBK&quot;?&gt;
&lt;web-app xmlns=&quot;http://xmlns.jcp.org/xml/ns/javaee&quot;
	xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xsi:schemaLocation=&quot;http://xmlns.jcp.org/xml/ns/javaee
	http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd&quot;
	version=&quot;3.1&quot;&gt;

2.4
&lt;!DOCTYPE web-app PUBLIC
 &quot;-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN&quot;
 &quot;http://java.sun.com/dtd/web-app_2_3.dtd&quot; &gt;
&lt;web-app&gt;

2.5
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;web-app xmlns=&quot;http://java.sun.com/xml/ns/javaee&quot;
           xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
           xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/javaee
		  http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&quot;
           version=&quot;2.5&quot;&gt;

&lt;/web-app&gt;
</code></pre>
<h1 id="q--a">Q &amp; A</h1>
<h2 id="attribute与parameter区别">attribute与parameter区别</h2>
<p>1、request.getParameter取得Web客户端到web服务端的http请求数据(get/post)，只能是string类型的</p>
<p>2、request.getAttribute():当两个web组件为转发关系时，通过getAttribute()和setAttribute()来共享request范围内的数据。attrubute中的数据是Object类型的，通过attribute传递的数据只会存在于web容器内部，仅仅是请求处理阶段。</p>
<p>3、小结：request.getAttribute()方法返回request范围内存在的对象，request.getParameter()获取http请求提交过来的数据（字符串）。</p>
<h2 id="jsp内置对象--el表达式内置对象">JSP内置对象 &amp; EL表达式内置对象</h2>
<p>JSP内置对象：</p>
<pre><code>application

config
exception
out

page

pageContext

request
response
session
</code></pre>
<p>EL表达式内置对象：</p>
<pre><code>pageContext

pageScope
requestScope
sessionScope
applicationScope

param
paramValues
header
headerValues
cookie
initParam
</code></pre>
<h2 id="转发重定向区别">转发、重定向区别</h2>
<p>转发（forward)：将请求forward到指定jsp资源</p>
<p>重定向（redirect）：比喻：你找我借钱，我没有，叫你去找他</p>
<p>区别：重定向会丢失所有的请求参数、请求属性、action的处理结果，url会改变。发送再次请求。</p>
<h2 id="默认跳转到indexjsp">默认跳转到index.jsp</h2>
<p>Java Web项目，启动tomcat后默认到跳转到webapp下的index.jsp，除非web.xml中配置其它欢迎页面。</p>
<h2 id="java-web中有几个域分别是什么怎么用">Java Web中有几个域，分别是什么，怎么用</h2>
<p>page/request/session/application域</p>
<h2 id="和的区别">&lt;%!%&gt;和&lt;%%&gt;的区别</h2>
<p>&lt;%!%&gt;只是进行方法的定义和属性的定义</p>
<p>&lt;%%&gt;这个里面定义的会<strong>转换成方法内的局部变量，或者代码</strong></p>
<p>&lt;%!%&gt;是用来定义成员变量属性和方法的,&lt;%%&gt;主要是用来输出内容的,因此如果涉及到了成员变量的操作,那么我们就应该使用&lt;!%%&gt;,而如果是涉及到了输出内容的时候,就使用&lt;%%&gt;。</p>
<p><a href="https://zhidao.baidu.com/question/253471013.html">https://zhidao.baidu.com/question/253471013.html</a></p>

    </div>
    <div class="article-footer">
<blockquote class="mt-2x">
  <ul class="post-copyright list-unstyled">
    <li class="post-copyright-link hidden-xs">
      <strong>Permalink: </strong>
      <a href="https://rulerLwx.gitee.io/2020/07/java-ee-servlet/" title="Java-EE-Servlet" target="_blank" rel="external">https://rulerLwx.gitee.io/2020/07/java-ee-servlet/</a>
    </li>
    <li class="post-copyright-license">
      <strong>License：</strong><a href="http://creativecommons.org/licenses/by/4.0/deed.zh" target="_blank" rel="external">CC BY 4.0 CN</a>
    </li>
  </ul>
</blockquote>

<div class="panel panel-default panel-badger">
  <div class="panel-body">
    <figure class="media">
      <div class="media-left">
        <a href="https://gitee.com/rulerLwx" target="_blank" class="img-burn thumb-sm visible-lg">
          <img src="https://rulerLwx.gitee.io/avatar.png" class="img-rounded w-full" alt="">
        </a>
      </div>
      <div class="media-body">
        <h3 class="media-heading"><a href="https://gitee.com/rulerLwx" target="_blank"><span class="text-dark">rulerLwx</span><small class="ml-1x">thinking...</small></a></h3>
        <div>Good Good Study, Day Day Up~</div>
      </div>
    </figure>
  </div>
</div>
    </div>
  </article>
<section id="comments">
    <div id="vcomments"></div>
</section>

</div><nav class="bar bar-footer clearfix" data-stick-bottom>
    <div class="bar-inner">
        <ul class="pager pull-left">
            <li class="prev">
                <a href="https://rulerLwx.gitee.io/2020/07/java-framework-activemq/" title="Java-framework-ActiveMQ"><i
                        class="icon icon-angle-left"
                        aria-hidden="true"></i><span>&nbsp;&nbsp;Older</span></a>
            </li>
            <li class="next">
                <a href="https://rulerLwx.gitee.io/2020/07/idea/"
                    title="IDEA"><span>Newer&nbsp;&nbsp;</span><i
                        class="icon icon-angle-right" aria-hidden="true"></i></a>
            </li>
            
            <li class="toggle-toc">
                <a class="toggle-btn collapsed" data-toggle="collapse" href="#collapseToc" aria-expanded="false"
                    title="Catalogue" role="button">
                    <span>[&nbsp;</span><span>Catalogue</span>
                    <i class="text-collapsed icon icon-anchor"></i>
                    <i class="text-in icon icon-close"></i>
                    <span>]</span>
                </a>
            </li>
        </ul>
        <div class="bar-right">
            <div class="share-component" data-sites="weibo,qq,wechat"
                data-mobile-sites="weibo,qq,qzone"></div>
        </div>
    </div>
</nav>

</main><footer class="footer" itemscope itemtype="http://schema.org/WPFooter">
<ul class="social-links">
    <li><a href="https://gitee.com/rulerLwx" target="_blank" title="gitee" data-toggle=tooltip data-placement=top >
            <i class="icon icon-gitee"></i></a></li>
    <li><a href="https://github.com/wolf-lea" target="_blank" title="github" data-toggle=tooltip data-placement=top >
            <i class="icon icon-github"></i></a></li>
</ul>
  <div class="copyright">
    &copy;2020  -
    2020
    <div class="publishby">
        Theme by <a href="https://github.com/xiaoheiAh" target="_blank"> xiaoheiAh </a>base on<a href="https://github.com/xiaoheiAh/hugo-theme-pure" target="_blank"> pure</a>.
    </div>
  </div>
</footer>

<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js?config=TeX-MML-AM_SVG"></script>
<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
            showMathMenu: false, //disables context menu
            tex2jax: {
            inlineMath: [ ['$','$'], ['\\(','\\)'] ]
           }
    });
</script>


<script src="https://cdn.jsdelivr.net/npm/jquery@3.4.1/dist/jquery.min.js"></script>
<script>
    window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')
</script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/highlight.min.js"></script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/languages/python.min.js" defer></script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/languages/javascript.min.js" defer></script><script>
    hljs.configure({
        tabReplace: '    ', 
        classPrefix: ''     
        
    })
    hljs.initHighlightingOnLoad();
</script>
<script src="https://rulerLwx.gitee.io/js/application.min.bdeb64b910570b6c41badc6a05b7afb0c8ad9efd8525de3c7257d59e786326a3.js"></script>
<script src="https://rulerLwx.gitee.io/js/plugin.min.51ff8c7317566f82259170fa36e09c4493adc9b9378b427a01ad3f017ebac7dd.js"></script>

<script>
    (function (window) {
        var INSIGHT_CONFIG = {
            TRANSLATION: {
                POSTS: 'Posts',
                PAGES: 'Pages',
                CATEGORIES: 'Categories',
                TAGS: 'Tags',
                UNTITLED: '(Untitled)',
            },
            ROOT_URL: 'https:\/\/rulerLwx.gitee.io',
            CONTENT_URL: 'https:\/\/rulerLwx.gitee.io\/searchindex.json ',
        };
        window.INSIGHT_CONFIG = INSIGHT_CONFIG;
    })(window);
</script>
<script type="text/javascript" src="https://rulerLwx.gitee.io/js/insight.min.a343cd9a5a7698336b28ef3a7c16a3a1b1d2d5fb17dc8ed04022bbe08cc5459073a15bdafa3a8a58cdd56080784bdd69fa70b1ae8597565c799c57ed00f0e120.js" defer></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.4.2/tocbot.min.js"></script>
<script>
    tocbot.init({
        
        tocSelector: '.js-toc',
        
        contentSelector: '.js-toc-content',
        
        headingSelector: 'h1, h2, h3',
        
        hasInnerContainers: true,
    });
</script>

<script src="https://cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine"></script>
<script type="text/javascript">
    var GUEST = ['nick', 'mail', 'link'];
    var meta = 'nick,mail';
    meta = meta.split(',').filter(function (item) {
        return GUEST.indexOf(item) > -1;
    });
    new Valine({
        el: '#vcomments',
        verify: null ,
        notify: null ,
        appId: 'IyAB0PSPRazTPDxitO1ddQ7O-gzGzoHsz',
        appKey: '5rBJTq4KidYF33eXwvRVhtEH',
        placeholder: 'enjoy~',
        avatar: 'mm',
        meta: meta,
        pageSize: '10' || 10,
        visitor: false 
});
</script>

  </body>
</html>
